package com.laoyao.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.junit.Test;

import com.jfinal.aop.Before;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.laoyao.beans.JsCode;
import com.laoyao.util.DateUtil;
import com.laoyao.util.FileUtil;
import com.laoyao.util.HttpUtil;
import com.laoyao.util.MD5Util;
import com.laoyao.util.TextUtil;
import com.laoyao.util.UIDUtil;

public class WeixService {
	private String rootPath = PathKit.getWebRootPath();
	
	

	/**
	 * 根据sessionId获取用户实例
	 * @param sessionId
	 * @return
	 */
	
	public Record getUser(String sessionId){
		String sql = "select a.* from users a,user_status b where a.openId = b.openId and sessionId=?";
		return Db.findFirst(sql,sessionId);
	}
	/**
	 * 判断是否为旧图
	 * @param imgUrl
	 * @param sessionId
	 * @return
	 */
	public boolean isOld(String imgUrl,String sessionId){
		if(imgUrl==null)
			return false;
		String oldImg = getUser(sessionId).getStr("photo");
		return imgUrl.equals(oldImg);
	}
	
	public Record findUserByCountAndPwd(String username,String pwd){
		String sql = "select * from dietitian where dietitian_tel=? and dietitian_pwd=?";
		String pwd1 = MD5Util.GetMD5Code(pwd);
		System.out.println(pwd1);
		return Db.findFirst(sql,username,MD5Util.GetMD5Code(pwd));
	}
	
	/**
	 *
	 * @param code 小程序登录码
	 * @param user 正确登录获取到的用户
	 * @return  返回sessionId
	 */
	
	@Before(Tx.class)
	public String login(String code,Record user){
		String appid = PropKit.get("appid");
		String appsecret = PropKit.get("appsecret");
		//我是火车王！
		JsCode jscode =  HttpUtil.getJsCode(appid, appsecret, code);
		//出来吧！皮卡丘~(获取用户数据)
		
		
		//既然登录了，那么该重置的也应该重置一下了
		Record userStatus = new Record();
		userStatus.set("openId", jscode.getOpenid())
        .set("sessionKey", jscode.getSession_key())
        .set("sessionId",UIDUtil.getUUID()) //自己写的UUID工具类拉
        .set("timeOut", DateUtil.addDay(7)); //设置超期3天
		user.set("open_id", jscode.getOpenid());
		
		if(Db.findById("user_status","openId",user.getStr("open_id"))==null){
			//用户信息表保存新用户
			//user=new Record();
			//用户登录态保存新自定义登录态
			if(!(Db.update("dietitian","dietitian_id",user)&&Db.save("user_status", userStatus))){
				System.out.println("1这里返回空");
				return null;
			}
				
									
		}else{
			if(!Db.update("user_status", "openId",userStatus)){
				System.out.println("2这里返回空");
				return null;
			}
				
		}
		   
		
		return userStatus.getStr("sessionId");
	}
	/**
	 * 
	 * @return 返回客户来源列表
	 */
	public List<Record> getAllOrigin(){
		String sql = "select * from origin";
		return Db.find(sql);
	}
	/**
	 * 获取所有菜单信息
	 * @return
	 */
	public List<Record> findAllMenu(){
		String sql = "select * from menu";
		return Db.find(sql);
	}

/*	public boolean copyMenuMould(User user){
		String sql = "insert into nutrition(user_id,nutrition_week,nutrition_day,nutrition_food1,nutrition_food2,nutrition_food3,nutrition_food4,nutrition_food5,nutrition_food6)"
               +"select user_id,menu_week,menu_day,menu_food1,menu_food2,menu_food3,menu_food4,menu_food5,menu_food6 from user,menu_mould where user.menu_id=menu_mould.menu_id and user_id=?";

		String start = user.getUserStart().split(",")[0]; //预定开始时间
		String end = user.getUserEnd().split(",")[0]; //预定结束时间
		String start1 = user.getUserStart().split(",")[1]; //早中晚
		String end1 = user.getUserEnd().split(",")[1]; //早中晚
		Integer userId = user.getUserId(); //用户id（其实是订单）
		Integer nutrition_week = user.getNutritionWeek();
		String sql = "select user_id,menu_week,menu_day,menu_food1,menu_food2,menu_food3,menu_food4,menu_food5,menu_food6 from user,menu_mould where user.menu_id=menu_mould.menu_id and user_id=?";
		sql+=" order by menu_week asc,menu_day asc";
		List<Record> list = Db.find(sql,userId);
		List<Record> nttlist = new ArrayList<Record>();
		String time = start;
		Integer day = DateUtil.getDay(start);
		
		System.out.println(nutrition_week+"-----"+list.size());
		(day+6)%7 = ?,将0代表周日转化成6代表周日。 0 1 2 3 4 5 6 代表周一周二周三周四周五周六周日 
		
		for (int i = (nutrition_week-1)*7+(day+6)%7; i < list.size(); i++) {
			Record item = list.get(i);
			Record item2 = new Record();
			item2.set("user_id", item.get("user_id"))
					.set("nutrition_day", item.get("menu_day"))
					.set("nutrition_week", item.get("menu_week"))
					.set("nutrition_food1", item.get("menu_food1"))
					.set("nutrition_food2", item.get("menu_food2"))
					.set("nutrition_food3", item.get("menu_food3"))
					.set("nutrition_food4", item.get("menu_food4"))
					.set("nutrition_food5", item.get("menu_food5"))
					.set("nutrition_food6", item.get("menu_food6"))
					.set("nutrition_time", time);
			nttlist.add(item2);
			System.out.println(time);
			if (time.equals(end))
				break;
			time = DateUtil.addyyyyMMdd(time, 1);
			if((i+1)==list.size()){
				if(list.size()<28)
					i=i-list.size();
				else
					i=i-14;
			}
				
		}
		int last  = nttlist.size();
		//判断从那餐开始选，没有选中的餐为空
		if(start1.equals("中")||start1.equals("晚")){
			nttlist.get(0).set("nutrition_food1", null)
		      .set("nutrition_food2", null);
		}
		if(start1.equals("晚")){
			nttlist.get(0).set("nutrition_food3", null)
		      .set("nutrition_food4", null);
		}
		
		if(end1.equals("中")||end1.equals("早")){
			nttlist.get(last-1).set("nutrition_food5", null)
		      .set("nutrition_food6", null);
		}
		if(end1.equals("早")){
			nttlist.get(last-1).set("nutrition_food3", null)
		      .set("nutrition_food4", null);
		}
		
		
		int[] b = Db.batchSave("nutrition", nttlist,nttlist.size());
		boolean flag = true;
		//int n=1;
		for(int i : b){
			//System.out.println(n+":"+i);
			//n++;
			if(i<=0)
				flag=false;//一条更新失败就返回错误
		}
		return true; 
	}*/
	
	
	/**
	 * 
	 * @param pageNumber 页码
	 * @param pageSize  页大小
	 * @param key  查询参数
	 * @param dietitian_id 营养师id
	 * @return
	 */
	public Page<Record> userList(Integer pageNumber ,Integer pageSize , String key ,String dietitian_id){
		String sql = "select * from user a, menu b where 1=1 and a.menu_id=b.menu_id and a.dietitian_id= "+dietitian_id;
		if(!TextUtil.isEmpty(key)){
			sql+=" and (a.user_name like'%"+key+"%' or a.user_tel like '%"+key+"%' )";
		}
		sql += " and isRenew=0 and user_state=0 order by a.user_id desc";
		
		//自动移除过期客户
		String sql1 = " update user a set a.user_state=2 where  "
				+ " not EXISTS(select * from nutrition b where a.user_id = b.user_id and b.nutrition_time>=?)"
				+ "  and not EXISTS(select * from nutrition c,renew d where a.user_id = d.order and c.user_id=d.renewOrder and  c.nutrition_time>=?)"
				+ "  and a.recoverTime<'"+DateUtil.getDate()+"'";
		
		String sql2 = "update user a set a.user_state=2 where "
				       		+ "EXISTS(select * from (select * from renew b,user c where c.user_state=2 and c.user_id=b.order) t where a.user_id=t.reneworder ) ";
		Db.update(sql1,DateUtil.getDate(),DateUtil.getDate());
		Db.update(sql2);
		return Db.paginate(pageNumber, pageSize,"",sql);
	}
	/**
	 * 
	 * @param pageNumber 页码
	 * @param pageSize  页大小
	 * @param key  查询参数
	 * @param dietitian_id 营养师id
	 * @return
	 */
	public Page<Record> userHistoryList(Integer pageNumber ,Integer pageSize , String key ,String dietitian_id){
		String sql = " user a, menu b where 1=1 and a.menu_id=b.menu_id and a.dietitian_id= "+dietitian_id;
		if(!TextUtil.isEmpty(key)){
			sql+=" and (a.user_name like'%"+key+"%' ) ";
		}
		sql += " and isRenew=0 and user_state=2 order by a.user_id desc";
		return Db.paginate(pageNumber, pageSize,"select * from" ,sql);
	}
	/**
	 * 
	 * @param id 营养师id
	 * @param date 日期
	 * @return
	 */
	public List<Record> getChangeMenu(String id,String date){
		String sql = "select * from update_a a, user b where a.user_id=b.user_id and a.dietitian_id=? and update_flag=1 and update_state=0 ";
//		sql += " and update_time between '"+date+"' and '"+DateUtil.addyyyyMMdd(date,1)+"' ";
		sql += " and nutrition_time between '"+DateUtil.addyyyyMMdd(date,1)+"' and '"+DateUtil.addyyyyMMdd(date,2)+"' ";
		sql+=" order by nutrition_time";
		return Db.find(sql,id);
	}
	public List<Record> getDietitianSubmit(String id){
		String sql = "select * from update_a a, user b where a.user_id=b.user_id and a.dietitian_id=? and update_flag=0 and update_state=0 ";
		sql += " order by update_id desc";
		return Db.find(sql,id);
	}
	/**
	 * 
	 * @param dietitian_id 营养师id
	 * @param nutrition_id 每天餐品 id
	 * @return
	 */
	public Record getChangeFood(String dietitian_id,String nutrition_id){
		String sql = "select *,a.nutrition_week nutrition_week from update_a a,user b,menu c "
				+ "where a.user_id=b.user_id and b.menu_id = c.menu_id and a.dietitian_id = ? and nutrition_id=?";
		return Db.findFirst(sql,dietitian_id,nutrition_id);
	}
	/**
	 * 
	 * @param dietitian_id 营养师id
	 * @return
	 */
	public List<Record> getHistory(String dietitian_id,String key){
		String sql ="select * from update_a a,user b,menu c"
				+ "  where a.user_id=b.user_id and b.menu_id=c.menu_id and b.dietitian_id =?";
		if(!TextUtil.isEmpty(key)){
			sql+= " and b.user_name like '%"+key+"%' ";
		}
		sql += " order by a.update_id desc";
		
		return Db.find(sql,dietitian_id);
	}
	
	/**
	 * 获取续费订单信息
	 * @param userId 主订单id
	 * @return
	 */
	public List<Record> getRenewMeal(String userId){
		String sql = "select * from renew a,user b,menu c where a.renewOrder = b.user_id"
				+ " and b.menu_id=c.menu_id  and a.order=?";
		return Db.find(sql,userId);
	}
	/**
	 * 上传尾款截图
	 * @param img
	 * @param userId
	 * @return
	 */
	public boolean saveBalancePayMentImg(String img,String userId){
		Record r = new Record();
		r.set("balancePaymentImg", img);
		r.set("user_id", userId);
		return Db.update("user","user_id",r);
	}
	
	
	public boolean repairMeal(String userId,String mealValue1,String mealValue2){
		String sql = "select * from nutrition where user_id=? order by nutrition_id desc";
		List<Record> list = Db.find(sql,userId);
		Record r = list.get(0);
		if(TextUtil.isEmpty(mealValue1))
			return false;
			
		
		//如果最后一天午餐为空，就补在午餐上面
		if(TextUtil.isEmpty(r.getStr("nutrition_food3"))&&TextUtil.isEmpty(r.getStr("nutrition_food5"))){
			r.set("nutrition_food3", mealValue1);
			r.set("nutrition_food4", mealValue2);
			return Db.update("nutrition","nutrition_id" ,r);
		}
		//如果最后一天晚餐为空，就补在最后一天晚餐
		if(TextUtil.isEmpty(r.getStr("nutrition_food5"))){
			r.set("nutrition_food5", mealValue1);
			r.set("nutrition_food6", mealValue2);
			return Db.update("nutrition","nutrition_id", r);
		}
		//午餐早餐都不为空，那么只能补到下一天了
		
		r.set("nutrition_time",DateUtil.addyyyyMMdd(r.getStr("nutrition_time"), 1));
		r.remove("nutrition_id");
		r.set("nutrition_food1", mealValue1);
		r.set("nutrition_food2", mealValue2);
		r.set("nutrition_food3", null);
		r.set("nutrition_food4", null);
		r.set("nutrition_food5", null);
		r.set("nutrition_food6", null);
		
			
		return Db.save("nutrition", r);
	}
	
	public boolean recoveryMeal(String nutrition_id,String userId,String mealName1){
		//先查询暂停缓存表数据
		String sql1 = "select * from meal_pause where nutrition_id=? and mealName1=?";
		Record pause = Db.findFirst(sql1,nutrition_id,mealName1);
		if(pause==null) return false;
		//接着表演真正的技术(恢复数据)
		String sql2 = "update nutrition set "+pause.getStr("mealName1")+"=?,"+pause.getStr("mealName2")+"=? where nutrition_id=?";
		Db.update(sql2,pause.getStr("mealValue1"),pause.getStr("mealValue2"),nutrition_id);
		//将最后一条数据的最后一餐置空
		String sql3 = "select * from nutrition where user_id="+userId+" order by nutrition_time desc";
		List<Record> list = Db.find(sql3);
		Record r = list.get(0);
		int i=0;
		while(true){
			//晚餐不为空那么晚餐就是最后一餐，移除之
			if(!TextUtil.isEmpty(r.getStr("nutrition_food5"))){
				r.set("nutrition_food5",null);
				r.set("nutrition_food6",null);
				return Db.update("nutrition","nutrition_id",r);
			}
			
			//前面已经确定晚餐为空了，如果午餐还是不为空，那么午餐就是最后一餐，移除之
			if(!TextUtil.isEmpty(r.getStr("nutrition_food3"))){
				r.set("nutrition_food3",null);
				r.set("nutrition_food4",null);
				return Db.update("nutrition","nutrition_id",r);
			}
			//午餐晚餐都是为空那么早餐就是最后一餐，好办！
			
			if(!TextUtil.isEmpty(r.getStr("nutrition_food1"))){
				return Db.delete("nutrition","nutrition_id",r);
			}
			Db.delete("nutrition","nutrition_id",r);
			r=list.get(++i);	
		}
		
		
		
	}
	

	
	//补餐
	public String[] appendMeal(String userId,String menuId){
		
		//获取菜单列表
		String sql = "select * from menu a,menu_mould b where a.menu_id=b.menu_id and a.menu_id=?";		
		List<Record> menus = Db.find(sql,menuId);
		//获取用户订餐数据
		sql = "select * from nutrition where user_id = ? order by nutrition_time desc";
		List<Record> nttlist = Db.find(sql,userId);
		
		//获取最后一天订餐情况
		Record lastmeal = nttlist.get(0);	

		//判断需要补哪一餐
		int flag=0; //都不为空，补下一天
		if(TextUtil.isEmpty(lastmeal.getStr("nutrition_food5")))//晚餐为空，补晚餐
			flag=2;
		if(TextUtil.isEmpty(lastmeal.getStr("nutrition_food3"))&&TextUtil.isEmpty(lastmeal.getStr("nutrition_food5")))//午餐为空，补午餐
			flag=1;
		
		
		//判断最后一天处于哪个阶段 nttlist.size()/7
		int size = nttlist.size();
		int leftDay =size%7; //该阶段剩余天数
		int stage = size/7;  //当前阶段
		//获取最后一天出餐是周几,0代表周一
		int day = (DateUtil.getDay(lastmeal.getStr("nutrition_time"))+6)%7;
		int whereWeek = (DateUtil.getWeekNum("2018-12-24")+1)%2;//单周的值为0，双周的值为1
		int flag_num = (stage/2*2)/(stage/2+1);
		int index = flag_num*2*7+stage%2*7 + day%7;
		
		//从菜单表中获取补餐信息
		String [] meals = new String[2];
		switch (flag) {
		case 0:
			stage=stage+(7-leftDay)/7;//(7-leftDay)/7 判断是否进位,剩余天数为0进位
			/*(stage/2*2)/(stage/2+1) 判断stage是否大于等于2,大于等于2值恒为1*/
			flag_num = (stage/2*2)/(stage/2+1);
			index = flag_num*2*7+stage%2*7 + (day + 1)%7;
			
			/*
			 * 处理第三阶段为14天的情况
			 * flag_num^1 异或，当flag_num=1,异或值为0,令stage%恒为0
			 */
			if(menus.get(0).getInt("menu_type")==1)
				index = (flag_num*2*7+(stage%2)*(flag_num^1)*7 + whereWeek*7+(day + 1)%7);
			
			meals[0] = menus.get(index).getStr("menu_food1");
			meals[1] = menus.get(index).getStr("menu_food2");
			break;
		case 1:
			meals[0] = menus.get(index).getStr("menu_food3");
			meals[1] = menus.get(index).getStr("menu_food4");
			break;
		case 2:
			meals[0] = menus.get(index).getStr("menu_food5");
			meals[1] = menus.get(index).getStr("menu_food6");
			break;
		}
						
		return meals;
	}
		
	
}
